package com.lyf.shop.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyf.shop.constant.LoginConstant;
import com.lyf.shop.entity.User;
import com.lyf.shop.service.UserService;
//import com.sun.deploy.net.HttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2021-12-01 16:50:07
 */
@RequestMapping("user")
@Controller
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    //登录
    @RequestMapping("login")
    public String login(@RequestParam("name") String loginName, @RequestParam("pwd") String pwd, HttpSession httpSession, RedirectAttributesModelMap model) {
        User user = (User) httpSession.getAttribute(LoginConstant.LOGIN_USER_KEY);
        if (user == null) {
            User query = new User();
            query.setLoginName(loginName);
            query.setPwd(pwd);
            user = userService.queryByUser(query);
            if (user == null) {
                model.addFlashAttribute("msg", "用户名或密码错误！");
                return "redirect:/user/toLogin";
            } else {
                httpSession.setAttribute(LoginConstant.LOGIN_USER_KEY, user);
            }
        }
        return "/jsp/index";
    }

    //进入登录页面
    @RequestMapping("toLogin")
    public String toLogin() {
        return "/jsp/login";
    }

    //退出登录页面
    @RequestMapping("logOut")
    public String toLogin(HttpSession httpSession) {
        httpSession.removeAttribute(LoginConstant.LOGIN_USER_KEY);
        return "/jsp/login";
    }

    //注册
    @PostMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(User user) throws JsonProcessingException {
        Map<String, Object> result = userService.addUser(user);
        return result;
    }
}